package com.example.singing.view;

import com.example.singing.manager.CompetitionManager;
import com.example.singing.manager.TeamManager;
import com.example.singing.manager.ScoreManager;
import com.example.singing.model.Competition;
import com.example.singing.model.Team;
import com.example.singing.model.User;
import com.example.singing.util.AlertUtil;
import javafx.collections.FXCollections;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.stage.FileChooser;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 队伍管理界面
 */
public class TeamView {
    private VBox view;
    private TeamManager teamManager;
    private CompetitionManager competitionManager;
    private ScoreManager scoreManager;
    private VBox teamCardsContainer; // 用于容纳队伍卡片的容器
    private ScrollPane scrollPane;
    private HBox buttonBox;
    private ComboBox<Competition> competitionComboBox; // 用于选择比赛的下拉框
    private User currentUser; // 当前用户

    // 无参构造函数，保留兼容性
    public TeamView() {
        this.teamManager = new TeamManager();
        this.competitionManager = new CompetitionManager();
        this.scoreManager = new ScoreManager();
        this.currentUser = null;
        createView();
    }

    // 带用户参数的构造函数
    public TeamView(User user) {
        this.teamManager = new TeamManager();
        this.competitionManager = new CompetitionManager();
        this.scoreManager = new ScoreManager();
        this.currentUser = user;
        createView();
    }

    /**
     * 创建队伍管理界面
     */
    private void createView() {
        VBox teamsView = new VBox(20);
        teamsView.setPadding(new Insets(20));
        teamsView.setStyle("-fx-background-color: #f5f5f5;");

        // 比赛选择和操作按钮区域
        HBox topBox = new HBox(15);
        topBox.setAlignment(javafx.geometry.Pos.CENTER_LEFT);
        topBox.setPadding(new Insets(10));
        topBox.setStyle("-fx-background-color: white; -fx-background-radius: 10; -fx-effect: dropshadow(gaussian, rgba(0,0,0,0.1), 10, 0, 0, 5);");

        // 比赛选择下拉框
        Label competitionLabel = new Label("选择比赛:");
        competitionLabel.setStyle("-fx-font-weight: bold; -fx-text-fill: #212121;");
        competitionComboBox = new ComboBox<>();
        competitionComboBox.setPrefWidth(200);
        competitionComboBox.setStyle("-fx-border-color: #ddd; -fx-border-radius: 5;");
        loadCompetitions(); // 加载比赛数据到下拉框
        competitionComboBox.setOnAction(e -> refreshTeamCards()); // 选择比赛后刷新队伍卡片

        // 操作按钮
        buttonBox = new HBox(15);
        Button addBtn = new Button("添加队伍");
        addBtn.setStyle("-fx-background-color: #4caf50; -fx-text-fill: white; -fx-pref-width: 100;");
        addBtn.setOnAction(e -> showAddTeamDialog());

        Button refreshBtn = new Button("刷新");
        refreshBtn.setStyle("-fx-background-color: #2196f3; -fx-text-fill: white; -fx-pref-width: 100;");
        refreshBtn.setOnAction(e -> {
            loadCompetitions();
            refreshTeamCards();
        });

        buttonBox.getChildren().addAll(addBtn, refreshBtn);
        topBox.getChildren().addAll(competitionLabel, competitionComboBox, new Pane() {{ HBox.setHgrow(this, Priority.ALWAYS); }}, buttonBox);

        // 队伍卡片容器
        scrollPane = new ScrollPane();
        scrollPane.setPrefHeight(600);
        scrollPane.setFitToWidth(true);
        scrollPane.setStyle("-fx-background-color: transparent; -fx-border-color: transparent;");

        // 创建卡片容器
        teamCardsContainer = new VBox(15);
        teamCardsContainer.setPadding(new Insets(10));
        teamCardsContainer.setStyle("-fx-background-color: transparent;");

        // 将卡片容器放入滚动条
        scrollPane.setContent(teamCardsContainer);

        // 初始化队伍卡片列表
        refreshTeamCards();

        teamsView.getChildren().addAll(topBox, scrollPane);
        this.view = teamsView;
    }

    /**
     * 加载比赛数据到下拉框
     */
    private void loadCompetitions() {
        List<Competition> competitions = competitionManager.getAllCompetitions();
        competitionComboBox.setItems(FXCollections.observableArrayList(competitions));
        // 默认选中第一个比赛
        if (!competitions.isEmpty()) {
            competitionComboBox.getSelectionModel().select(0);
        }
    }

    /**
     * 刷新队伍卡片列表
     */
    private void refreshTeamCards() {
        teamCardsContainer.getChildren().clear();
        Competition selectedCompetition = competitionComboBox.getValue();
        
        if (selectedCompetition == null) {
            // 如果没有选择比赛，显示提示信息
            Label noCompetitionLabel = new Label("请先选择一个比赛");
            noCompetitionLabel.setStyle("-fx-font-size: 16px; -fx-text-fill: #999;");
            noCompetitionLabel.setPadding(new Insets(50));
            noCompetitionLabel.setAlignment(Pos.CENTER);
            teamCardsContainer.getChildren().add(noCompetitionLabel);
            return;
        }
        
        // 获取与当前比赛相关的队伍
        List<Team> teams = teamManager.getAllTeams().stream()
                .filter(team -> selectedCompetition.getId().equals(team.getCompetitionId()))
                .toList();
        
        if (teams.isEmpty()) {
            // 如果当前比赛没有队伍，显示提示信息
            Label noTeamsLabel = new Label("当前比赛还没有队伍，点击'添加队伍'按钮添加");
            noTeamsLabel.setStyle("-fx-font-size: 16px; -fx-text-fill: #999;");
            noTeamsLabel.setPadding(new Insets(50));
            noTeamsLabel.setAlignment(Pos.CENTER);
            teamCardsContainer.getChildren().add(noTeamsLabel);
        } else {
            // 为每个队伍创建卡片
            for (Team team : teams) {
                VBox teamCard = createTeamCard(team);
                teamCardsContainer.getChildren().add(teamCard);
            }
        }
    }

    /**
     * 创建队伍卡片
     */
    private VBox createTeamCard(Team team) {
        VBox card = new VBox(10);
        card.setPadding(new Insets(15));
        card.setStyle("-fx-background-color: white; -fx-background-radius: 10; -fx-effect: dropshadow(gaussian, rgba(0,0,0,0.1), 10, 0, 0, 5);");
        card.setPrefWidth(600);

        // 卡片悬停效果
        card.setOnMouseEntered(e -> {
            card.setStyle("-fx-background-color: white; -fx-background-radius: 10; -fx-effect: dropshadow(gaussian, rgba(0,0,0,0.2), 15, 0, 0, 8);");
        });
        card.setOnMouseExited(e -> {
            card.setStyle("-fx-background-color: white; -fx-background-radius: 10; -fx-effect: dropshadow(gaussian, rgba(0,0,0,0.1), 10, 0, 0, 5);");
        });

        // 卡片头部 - 队伍名称和ID
        HBox headerBox = new HBox(10);
        headerBox.setAlignment(Pos.CENTER_LEFT);
        Label nameLabel = new Label(team.getName());
        nameLabel.setStyle("-fx-font-size: 18px; -fx-font-weight: bold; -fx-text-fill: #212121;");
        Label idLabel = new Label("ID: " + team.getId());
        idLabel.setStyle("-fx-font-size: 12px; -fx-text-fill: #666;");
        headerBox.getChildren().addAll(nameLabel, new Pane() {{ HBox.setHgrow(this, Priority.ALWAYS); }}, idLabel);

        // 卡片内容 - 照片和信息
        HBox contentBox = new HBox(15);

        // 照片区域
        ImageView photoView = new ImageView();
        photoView.setFitWidth(120);
        photoView.setFitHeight(120);
        photoView.setStyle("-fx-border-color: #ddd; -fx-border-radius: 5;");
        photoView.setPreserveRatio(true);
        photoView.setSmooth(true);

        // 设置照片
        if (team.getPhotoPath() != null) {
            try {
                File photoFile = new File(team.getPhotoPath());
                if (photoFile.exists()) {
                    photoView.setImage(new Image(photoFile.toURI().toString()));
                } else {
                    // 使用默认图片
                    photoView.setImage(new Image(""));
                }
            } catch (Exception e) {
                // 使用默认图片
                photoView.setImage(new Image(""));
            }
        } else {
            // 使用默认图片
            photoView.setImage(new Image(""));
        }

        // 信息区域
        VBox infoBox = new VBox(5);
        infoBox.setPrefWidth(400);
        infoBox.getChildren().addAll(
                createInfoLabel("成员: " + String.join(", ", team.getMembers())),
                createInfoLabel("联系方式: " + team.getContactInfo())
        );

        // 操作按钮 - 根据用户角色显示
        if (currentUser != null && "管理员".equals(currentUser.getRole())) {
            HBox buttonBox = new HBox(10);
            Button editBtn = new Button("修改");
            editBtn.setStyle("-fx-background-color: #2196f3; -fx-text-fill: white; -fx-pref-width: 80;");
            editBtn.setOnAction(e -> editTeam(team));

            Button deleteBtn = new Button("删除");
            deleteBtn.setStyle("-fx-background-color: #f44336; -fx-text-fill: white; -fx-pref-width: 80;");
            deleteBtn.setOnAction(e -> deleteTeam(team));

            buttonBox.getChildren().addAll(editBtn, deleteBtn);
            infoBox.getChildren().add(buttonBox);
        } else {
            // 非管理员角色显示提示信息
            Label roleInfoLabel = new Label("仅管理员可修改和删除队伍");
            roleInfoLabel.setStyle("-fx-font-size: 12px; -fx-text-fill: #666; -fx-font-style: italic;");
            infoBox.getChildren().add(roleInfoLabel);
        }

        contentBox.getChildren().addAll(photoView, infoBox);
        card.getChildren().addAll(headerBox, contentBox);

        return card;
    }

    /**
     * 创建信息标签
     */
    private Label createInfoLabel(String text) {
        Label label = new Label(text);
        label.setStyle("-fx-font-size: 14px; -fx-text-fill: #333;");
        label.setWrapText(true);
        return label;
    }

    /**
     * 显示添加队伍对话框
     */
    private void showAddTeamDialog() {
        Competition selectedCompetition = competitionComboBox.getValue();
        if (selectedCompetition == null) {
            AlertUtil.showErrorAlert("错误", "请先选择一个比赛");
            return;
        }

        Dialog<Team> dialog = new Dialog<>();
        dialog.setTitle("添加队伍");
        dialog.setHeaderText("为比赛 '" + selectedCompetition.getName() + "' 添加队伍");

        // 设置按钮类型
        ButtonType saveButtonType = new ButtonType("保存", ButtonBar.ButtonData.OK_DONE);
        dialog.getDialogPane().getButtonTypes().addAll(saveButtonType, ButtonType.CANCEL);

        // 创建主容器
        VBox mainContainer = new VBox(15);
        mainContainer.setPadding(new Insets(10));

        // 创建内容框（表单和图片区域）
        HBox contentBox = new HBox(20);
        contentBox.setAlignment(Pos.CENTER);

        // 左侧表单
        GridPane grid = new GridPane();
        grid.setHgap(10);
        grid.setVgap(10);
        grid.setPadding(new Insets(10));
        grid.getStyleClass().add("form-grid");
        grid.setStyle("-fx-background-color: white; -fx-background-radius: 10; -fx-padding: 20; -fx-effect: dropshadow(gaussian, rgba(0,0,0,0.1), 10, 0, 0, 5);");

        // 自动生成唯一的队伍ID
        String generatedId = teamManager.generateTeamId();
        TextField idField = new TextField(generatedId);
        idField.setDisable(true); // 禁用编辑，防止用户修改
        idField.setStyle("-fx-border-color: #ddd; -fx-border-radius: 5; -fx-opacity: 0.7;");

        TextField nameField = new TextField();
        nameField.setPromptText("队伍名称");
        nameField.setPrefWidth(200);
        nameField.setStyle("-fx-border-color: #ddd; -fx-border-radius: 5;");

        TextField membersField = new TextField();
        membersField.setPromptText("成员 (用逗号分隔)");
        membersField.setPrefWidth(200);
        membersField.setStyle("-fx-border-color: #ddd; -fx-border-radius: 5;");

        TextField contactField = new TextField();
        contactField.setPromptText("联系方式");
        contactField.setPrefWidth(200);
        contactField.setStyle("-fx-border-color: #ddd; -fx-border-radius: 5;");

        // 添加标签和字段到网格
        grid.add(new Label("队伍ID: *"), 0, 0);
        grid.add(idField, 1, 0);
        grid.add(new Label("队伍名称: *"), 0, 1);
        grid.add(nameField, 1, 1);
        grid.add(new Label("成员: *"), 0, 2);
        grid.add(membersField, 1, 2);
        grid.add(new Label("联系方式: *"), 0, 3);
        grid.add(contactField, 1, 3);

        // 右侧图片上传和预览区域
        VBox imageBox = new VBox(15);
        imageBox.setAlignment(Pos.CENTER);
        imageBox.setStyle("-fx-background-color: white; -fx-background-radius: 10; -fx-padding: 20; -fx-effect: dropshadow(gaussian, rgba(0,0,0,0.1), 10, 0, 0, 5);");
        
        // 图片预览
        ImageView previewImageView = new ImageView();
        previewImageView.setFitWidth(180);
        previewImageView.setFitHeight(140);
        previewImageView.setStyle("-fx-border-color: #ddd; -fx-border-radius: 5;");
        previewImageView.setPreserveRatio(true);
        previewImageView.setSmooth(true);
        
        // 上传按钮
        Button uploadButton = new Button("上传队伍照片");
        uploadButton.setStyle("-fx-background-color: #2196f3; -fx-text-fill: white; -fx-pref-width: 150;");
        
        // 存储上传的图片路径
        final String[] imagePath = {null};
        
        uploadButton.setOnAction(e -> {
            FileChooser fileChooser = new FileChooser();
            fileChooser.setTitle("选择队伍照片");
            fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("图片文件", "*.png", "*.jpg", "*.jpeg", "*.gif", "*.bmp")
            );
            File selectedFile = fileChooser.showOpenDialog(dialog.getDialogPane().getScene().getWindow());
            
            if (selectedFile != null) {
                try {
                    // 创建存储图片的目录
                    File imagesDir = new File("user_uploads");
                    if (!imagesDir.exists()) {
                        imagesDir.mkdir();
                    }
                    
                    // 生成唯一的文件名
                    String timestamp = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
                    String extension = getFileExtension(selectedFile);
                    String newFileName = timestamp + "." + extension;
                    File destFile = new File(imagesDir, newFileName);
                    
                    // 复制文件
                    Files.copy(selectedFile.toPath(), destFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
                    
                    // 保存相对路径
                    imagePath[0] = "user_uploads/" + newFileName;
                    
                    // 显示预览
                    previewImageView.setImage(new Image(destFile.toURI().toString()));
                    
                } catch (IOException ex) {
                    AlertUtil.showErrorAlert("上传失败", "图片上传出错: " + ex.getMessage());
                }
            }
        });

        // 添加说明文字
        Label imageDesc = new Label("可选：上传队伍照片");
        imageDesc.setStyle("-fx-font-size: 12px; -fx-text-fill: #666;");
        
        imageBox.getChildren().addAll(previewImageView, uploadButton, imageDesc);

        // 将表单和图片区域添加到内容框
        contentBox.getChildren().addAll(grid, imageBox);
        
        // 添加底部说明
        Label requiredNote = new Label("* 表示必填项");
        requiredNote.setStyle("-fx-font-size: 12px; -fx-text-fill: #ff6b6b;");
        requiredNote.setAlignment(Pos.CENTER_LEFT);
        
        mainContainer.getChildren().addAll(contentBox, requiredNote);
        
        dialog.getDialogPane().setContent(mainContainer);

        // 将结果转换为队伍对象
        dialog.setResultConverter(dialogButton -> {
            if (dialogButton == saveButtonType) {
                if (idField.getText().isEmpty() || nameField.getText().isEmpty() ||
                        membersField.getText().isEmpty() || contactField.getText().isEmpty()) {
                    AlertUtil.showErrorAlert("输入错误", "请填写所有必填字段");
                    return null;
                }

                // 解析成员列表
                String[] membersArray = membersField.getText().split(",");
                List<String> members = new ArrayList<>();
                for (String member : membersArray) {
                    members.add(member.trim());
                }

                Team team = new Team(
                        idField.getText(),
                        nameField.getText(),
                        members,
                        contactField.getText()
                );
                
                // 设置关联的比赛ID
                team.setCompetitionId(selectedCompetition.getId());
                
                // 设置照片路径
                if (imagePath[0] != null) {
                    team.setPhotoPath(imagePath[0]);
                }
                
                return team;
            }
            return null;
        });

        // 显示对话框并处理结果
        dialog.showAndWait().ifPresent(team -> {
            teamManager.addTeam(team);
            refreshTeamCards();
            AlertUtil.showInfoAlert("成功", "队伍已添加");
        });
    }

    /**
     * 编辑队伍
     */
    private void editTeam(Team team) {
        Dialog<Team> dialog = new Dialog<>();
        dialog.setTitle("修改队伍");
        dialog.setHeaderText("修改队伍信息");

        ButtonType saveButtonType = new ButtonType("保存", ButtonBar.ButtonData.OK_DONE);
        dialog.getDialogPane().getButtonTypes().addAll(saveButtonType, ButtonType.CANCEL);

        // 创建主容器
        VBox mainContainer = new VBox(15);
        mainContainer.setPadding(new Insets(10));

        // 创建内容框（表单和图片区域）
        HBox contentBox = new HBox(20);
        contentBox.setAlignment(Pos.CENTER);

        // 左侧表单
        GridPane grid = new GridPane();
        grid.setHgap(10);
        grid.setVgap(10);
        grid.setPadding(new Insets(10));
        grid.getStyleClass().add("form-grid");
        grid.setStyle("-fx-background-color: white; -fx-background-radius: 10; -fx-padding: 20; -fx-effect: dropshadow(gaussian, rgba(0,0,0,0.1), 10, 0, 0, 5);");

        // 表单字段
        TextField idField = new TextField(team.getId());
        idField.setDisable(true);
        idField.setPrefWidth(200);
        idField.setStyle("-fx-border-color: #ddd; -fx-border-radius: 5;");

        TextField nameField = new TextField(team.getName());
        nameField.setPrefWidth(200);
        nameField.setStyle("-fx-border-color: #ddd; -fx-border-radius: 5;");

        TextField membersField = new TextField(String.join(", ", team.getMembers()));
        membersField.setPrefWidth(200);
        membersField.setStyle("-fx-border-color: #ddd; -fx-border-radius: 5;");

        TextField contactField = new TextField(team.getContactInfo());
        contactField.setPrefWidth(200);
        contactField.setStyle("-fx-border-color: #ddd; -fx-border-radius: 5;");

        // 添加标签和字段到网格
        grid.add(new Label("队伍ID: *"), 0, 0);
        grid.add(idField, 1, 0);
        grid.add(new Label("队伍名称: *"), 0, 1);
        grid.add(nameField, 1, 1);
        grid.add(new Label("成员: *"), 0, 2);
        grid.add(membersField, 1, 2);
        grid.add(new Label("联系方式: *"), 0, 3);
        grid.add(contactField, 1, 3);

        // 右侧图片上传和预览区域
        VBox imageBox = new VBox(15);
        imageBox.setAlignment(Pos.CENTER);
        imageBox.setStyle("-fx-background-color: white; -fx-background-radius: 10; -fx-padding: 20; -fx-effect: dropshadow(gaussian, rgba(0,0,0,0.1), 10, 0, 0, 5);");
        
        // 图片预览
        ImageView previewImageView = new ImageView();
        previewImageView.setFitWidth(180);
        previewImageView.setFitHeight(140);
        previewImageView.setStyle("-fx-border-color: #ddd; -fx-border-radius: 5;");
        previewImageView.setPreserveRatio(true);
        previewImageView.setSmooth(true);
        
        // 显示当前照片（如果有）
        if (team.getPhotoPath() != null) {
            try {
                File currentImageFile = new File(team.getPhotoPath());
                if (currentImageFile.exists()) {
                    previewImageView.setImage(new Image(currentImageFile.toURI().toString()));
                }
            } catch (Exception e) {
                System.err.println("加载当前照片出错: " + e.getMessage());
            }
        }
        
        // 存储上传的图片路径（初始为当前路径）
        final String[] imagePath = {team.getPhotoPath()};
        
        // 上传按钮
        Button uploadButton = new Button("上传队伍照片");
        uploadButton.setStyle("-fx-background-color: #2196f3; -fx-text-fill: white; -fx-pref-width: 150;");
        
        uploadButton.setOnAction(e -> {
            FileChooser fileChooser = new FileChooser();
            fileChooser.setTitle("选择队伍照片");
            fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("图片文件", "*.png", "*.jpg", "*.jpeg", "*.gif", "*.bmp")
            );
            File selectedFile = fileChooser.showOpenDialog(dialog.getDialogPane().getScene().getWindow());
            
            if (selectedFile != null) {
                try {
                    // 创建存储图片的目录
                    File imagesDir = new File("user_uploads");
                    if (!imagesDir.exists()) {
                        imagesDir.mkdir();
                    }
                    
                    // 生成唯一的文件名
                    String timestamp = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
                    String extension = getFileExtension(selectedFile);
                    String newFileName = timestamp + "." + extension;
                    File destFile = new File(imagesDir, newFileName);
                    
                    // 复制文件
                    Files.copy(selectedFile.toPath(), destFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
                    
                    // 保存相对路径
                    imagePath[0] = "user_uploads/" + newFileName;
                    
                    // 显示预览
                    previewImageView.setImage(new Image(destFile.toURI().toString()));
                    
                } catch (IOException ex) {
                    AlertUtil.showErrorAlert("上传失败", "图片上传出错: " + ex.getMessage());
                }
            }
        });

        // 移除照片按钮
        Button removeImageButton = new Button("移除照片");
        removeImageButton.setStyle("-fx-background-color: #ff9800; -fx-text-fill: white; -fx-pref-width: 150;");
        removeImageButton.setOnAction(e -> {
            imagePath[0] = null;
            previewImageView.setImage(null);
        });
        
        // 添加说明文字
        Label imageDesc = new Label("可选：修改队伍照片");
        imageDesc.setStyle("-fx-font-size: 12px; -fx-text-fill: #666;");
        
        imageBox.getChildren().addAll(previewImageView, uploadButton, removeImageButton, imageDesc);

        // 将表单和图片区域添加到内容框
        contentBox.getChildren().addAll(grid, imageBox);
        
        // 添加底部说明
        Label requiredNote = new Label("* 表示必填项");
        requiredNote.setStyle("-fx-font-size: 12px; -fx-text-fill: #ff6b6b;");
        requiredNote.setAlignment(Pos.CENTER_LEFT);
        
        mainContainer.getChildren().addAll(contentBox, requiredNote);
        
        dialog.getDialogPane().setContent(mainContainer);

        dialog.setResultConverter(dialogButton -> {
            if (dialogButton == saveButtonType) {
                if (nameField.getText().isEmpty() || membersField.getText().isEmpty() ||
                        contactField.getText().isEmpty()) {
                    AlertUtil.showErrorAlert("输入错误", "请填写所有必填字段");
                    return null;
                }

                // 解析成员列表
                String[] membersArray = membersField.getText().split(",");
                List<String> members = new ArrayList<>();
                for (String member : membersArray) {
                    members.add(member.trim());
                }

                Team updatedTeam = new Team(
                        idField.getText(),
                        nameField.getText(),
                        members,
                        contactField.getText()
                );
                
                // 保留原有的比赛关联
                updatedTeam.setCompetitionId(team.getCompetitionId());
                
                // 设置照片路径
                updatedTeam.setPhotoPath(imagePath[0]);
                
                return updatedTeam;
            }
            return null;
        });

        dialog.showAndWait().ifPresent(updatedTeam -> {
            teamManager.updateTeam(updatedTeam);
            refreshTeamCards();
            AlertUtil.showInfoAlert("成功", "队伍已更新");
        });
    }

    /**
     * 删除队伍
     */
    private void deleteTeam(Team team) {
        // 确认对话框
        Alert confirm = new Alert(Alert.AlertType.CONFIRMATION);
        confirm.setTitle("确认删除");
        confirm.setHeaderText("确定要删除此队伍吗？");
        confirm.setContentText("队伍ID: " + team.getId() + "\n队伍名称: " + team.getName() + 
                             "\n\n注意：删除队伍将同时删除所有相关的评分记录！");

        confirm.showAndWait().ifPresent(response -> {
            if (response == ButtonType.OK) {
                System.out.println("确认删除队伍: " + team.getId());
                
                // 使用级联删除，同时删除相关评分
                boolean deleted = teamManager.deleteTeamWithCascade(team.getId(), scoreManager);
                
                if (deleted) {
                    System.out.println("队伍删除成功，刷新界面");
                    refreshTeamCards();
                    AlertUtil.showInfoAlert("成功", "队伍及相关评分记录已删除");
                } else {
                    System.err.println("队伍删除失败");
                    AlertUtil.showErrorAlert("错误", "删除队伍失败，请重试");
                }
            }
        });
    }

    /**
     * 获取文件扩展名
     */
    private String getFileExtension(File file) {
        String name = file.getName();
        int lastDotIndex = name.lastIndexOf(".");
        if (lastDotIndex > 0 && lastDotIndex < name.length() - 1) {
            return name.substring(lastDotIndex + 1).toLowerCase();
        }
        return "";
    }

    /**
     * 获取界面视图
     */
    public VBox getView() {
        return view;
    }
}